package mi.payment.admin;

import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.sunmi.pay.hardware.aidlv2.AidlConstantsV2;
import com.sunmi.pay.hardware.aidlv2.readcard.CheckCardCallbackV2;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lainey.ui.dialog.EditTextDialog;
import lainey.ui.utils.LogUtil;
import lainey.ui.widget.TitleView;
import mi.payment.Constant;
import mi.payment.MyApplication;
import mi.payment.R;
import mi.payment.constants.Configs;
import mi.payment.settings.MerManagerSettings;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.transaction.ParamsCheckExt;
import mi.payment.ui.admin.ChangeInfoBySaveCodeActivity;
import mi.payment.ui.base.ParentActivity;

/**
 * 商户管理界面
 */
public class MerchantManagementSettingsActivity extends ParentActivity {

    private TextView mTvMID;
    private TextView mTvTID;
    private TextView mTvName;
    private TextView mTvNameEnglish;

    public static final int MERCHANT = 1;
    public static final int TERMINAL = 2;
    private static final int NAME_ZH = 3;
    private static final int NAME_EN = 4;
    private ParamsCheckExt mParamsCheckExt;
    private EditTextDialog mEditTextDialog;

    private RKI mRKI;
    private RKS mRKS;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.admin_activity_merchant_setting);
        initView();
        checkCard();
    }

    public void initView() {
        mRKI = new RKI(this);
        mRKS = new RKS(this);

        mParamsCheckExt = new ParamsCheckExt(this);

        TitleView titleView = findViewById(R.id.title_view);
        titleView.setCenterText(R.string.merchant_setting);
        titleView.setLeftImageOnClickListener(
                v -> onBackPressed()
        );

        View item = findViewById(R.id.item_merchant_num);
        item.findViewById(R.id.left_image).setVisibility(View.GONE);
        TextView leftText = item.findViewById(R.id.left_text);
        leftText.setText(R.string.merchant_num);
        mTvMID = item.findViewById(R.id.right_text);
        mTvMID.setText(R.string.unfilled);
        if (Configs.isEditMerchantInfo) {
            item.setOnClickListener(this);
            item.findViewById(R.id.right_image).setVisibility(View.VISIBLE);
        } else {
            item.findViewById(R.id.right_image).setVisibility(View.GONE);
        }

        item = findViewById(R.id.item_terminal_num);
        item.findViewById(R.id.left_image).setVisibility(View.GONE);
        leftText = item.findViewById(R.id.left_text);
        leftText.setText(R.string.merchant_terminal_num);
        mTvTID = item.findViewById(R.id.right_text);
        mTvTID.setText(R.string.unfilled);
        if (Configs.isEditMerchantInfo) {
            item.setOnClickListener(this);
            item.findViewById(R.id.right_image).setVisibility(View.VISIBLE);
        } else {
            item.findViewById(R.id.right_image).setVisibility(View.GONE);
        }

        item = findViewById(R.id.item_merchant_name);
        item.findViewById(R.id.left_image).setVisibility(View.GONE);
        leftText = item.findViewById(R.id.left_text);
        leftText.setText(R.string.merchant_name);
        mTvName = item.findViewById(R.id.right_text);
        mTvName.setText(R.string.unfilled);
        if (Configs.isEditMerchantInfo) {
            item.setOnClickListener(this);
            item.findViewById(R.id.right_image).setVisibility(View.VISIBLE);
        } else {
            item.findViewById(R.id.right_image).setVisibility(View.GONE);
        }

        item = findViewById(R.id.item_merchant_name_english);
        item.findViewById(R.id.left_image).setVisibility(View.GONE);
        leftText = item.findViewById(R.id.left_text);
        leftText.setText(R.string.merchant_name_english);
        mTvNameEnglish = item.findViewById(R.id.right_text);
        mTvNameEnglish.setText(R.string.unfilled);
        if (Configs.isEditMerchantInfo) {
            item.findViewById(R.id.right_image).setVisibility(View.VISIBLE);
            item.setOnClickListener(this);
        } else {
            item.findViewById(R.id.right_image).setVisibility(View.GONE);
        }

        findViewById(R.id.mb_rki).setOnClickListener(
                v -> mRKI.operate()
        );
        findViewById(R.id.mb_rks).setOnClickListener(
                v -> mRKS.operate()
        );
    }

    public void updateUI() {
        MerManagerSettings merchantManagerSettings = MerchantSettingsOperation.getInstance().getMerManagerSettings();
        // 商户号码
        String temp = merchantManagerSettings.getMerchantNum();
        temp = TextUtils.isEmpty(temp) ? "--" : temp;
        mTvMID.setText(temp);
        // 终端号码
        temp = merchantManagerSettings.getTerminalNum();
        temp = TextUtils.isEmpty(temp) ? "--" : temp;
        mTvTID.setText(temp);
        // 商户名称
        temp = merchantManagerSettings.getMerchantName();
        temp = TextUtils.isEmpty(temp) ? "--" : temp;
        mTvName.setText(temp);
        // 商户英文名
        temp = merchantManagerSettings.getMerchantEnglishName();
        temp = TextUtils.isEmpty(temp) ? "--" : temp;
        mTvNameEnglish.setText(temp);
    }

    @Override
    public void onBackPressed() {
        cancelCheckCard();
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        switch (id) {
            case R.id.item_merchant_num: // 商户号码
                boolean judge = mParamsCheckExt.isJudgeTradeNumber();
                if (judge) return;
                showEditTextDialog(MERCHANT);
                break;
            case R.id.item_terminal_num: // 终端号码
                judge = mParamsCheckExt.isJudgeTradeNumber();
                if (judge) return;
                showEditTextDialog(TERMINAL);
                break;
            case R.id.item_merchant_name: // 商户名称
                showEditTextDialog(NAME_ZH);
                break;
            case R.id.item_merchant_name_english: // 商户英文名
                showEditTextDialog(NAME_EN);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissEditTextDialog();
    }

    /**
     * 如果修改商户信息时不需要安全密码验证
     * 判断商户信息长度正确，直接保存
     */
    private void checkSafeCode(int index, String merchantInfo) {
        dismissEditTextDialog();
        if (Configs.isNeedSafeCode) {
            skipActivityTo(merchantInfo, index);
        } else {
            saveMerchantInfoByIndex(index, merchantInfo);
            updateUI();
        }
    }

    private void saveMerchantInfoByIndex(int index, String merchantInfo) {
        if (index == MERCHANT) {
            MerchantSettingsOperation.getInstance().saveMerchantNum(merchantInfo);
        } else if (index == TERMINAL) {
            MerchantSettingsOperation.getInstance().saveTerminalNum(merchantInfo);
        }
    }

    private void skipActivityTo(String info, int type) {
        Intent intent = new Intent(this, ChangeInfoBySaveCodeActivity.class);
        intent.putExtra("merchantInfo", info);
        intent.putExtra("merchantIndex", type);
        startActivity(intent);
    }

    private void showEditTextDialog(int type) {
        mEditTextDialog = new EditTextDialog(this);
        mEditTextDialog.setRightText(R.string.ok);
        mEditTextDialog.setLeftText(R.string.cancel);
        mEditTextDialog.setCanceledOnTouchOutside(true);
        mEditTextDialog.setCancelable(true);
        mEditTextDialog.setTextMode();
        mEditTextDialog.setLeftOnClickListener(
                v -> dismissEditTextDialog()
        );
        mEditTextDialog.setRightOnClickListener(
                v -> {
                    String text = mEditTextDialog.getText();
                    if (text.trim().length() > 0) {
                        if (type == MERCHANT && text.length() == 15) {
                            checkSafeCode(type, text);
                        } else if (type == TERMINAL && text.length() == 8) {
                            checkSafeCode(type, text);
                        } else if (type == NAME_ZH) {
                            MerchantSettingsOperation.getInstance().saveMerchantName(text);
                            dismissEditTextDialog();
                            updateUI();
                        } else if (type == NAME_EN) {
                            MerchantSettingsOperation.getInstance().saveMerchantEnglishName(text);
                            dismissEditTextDialog();
                            updateUI();
                        } else {
                            showToast(R.string.error_input);
                        }
                    } else {
                        showToast(R.string.error_input);
                    }
                }
        );

        MerManagerSettings merchantManagerSettings = MerchantSettingsOperation.getInstance().getMerManagerSettings();
        String temp;
        if (type == MERCHANT) {
            mEditTextDialog.setTitleText(R.string.merchant_num);
            mEditTextDialog.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
            mEditTextDialog.setMaxLength(15);
            temp = merchantManagerSettings.getMerchantNum();
        } else if (type == TERMINAL) {
            mEditTextDialog.setTitleText(R.string.merchant_terminal_num);
            mEditTextDialog.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
            mEditTextDialog.setMaxLength(8);
            temp = merchantManagerSettings.getTerminalNum();
        } else if (type == NAME_ZH) {
            mEditTextDialog.setTitleText(R.string.merchant_name);
            mEditTextDialog.setInputType(EditorInfo.TYPE_CLASS_TEXT);
            mEditTextDialog.setMaxLength(40);
            temp = merchantManagerSettings.getMerchantName();
        } else {
            mEditTextDialog.setTitleText(R.string.merchant_name_english);
            mEditTextDialog.setInputType(EditorInfo.TYPE_CLASS_TEXT);
            mEditTextDialog.setMaxLength(60);
            temp = merchantManagerSettings.getMerchantEnglishName();
        }
        boolean equals = TextUtils.isEmpty(temp) || TextUtils.equals(getString(R.string.unfilled), temp);
        if (equals) {
            mEditTextDialog.setText("");
        } else {
            mEditTextDialog.setText(temp);
        }
        try {
            mEditTextDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dismissEditTextDialog() {
        if (mEditTextDialog != null) {
            mEditTextDialog.dismiss();
        }
    }

    /**
     * 是否包含中文
     *
     * @param str 检测的字符串
     * @return true:包含 false:不包含
     */
    private boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }

    private void checkCard() {
        try {
            MyApplication.getInstance().mReadCardOptV2.checkCard(AidlConstantsV2.CardType.IC.getValue(), mCheckCardCallback, 60);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void cancelCheckCard() {
        try {
            MyApplication.getInstance().mReadCardOptV2.cancelCheckCard();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private CheckCardCallbackV2 mCheckCardCallback = new CheckCardCallbackV2.Stub() {

        @Override
        public void findMagCard(Bundle bundle) throws RemoteException {

        }

        @Override
        public void findICCard(String atr) throws RemoteException {
            LogUtil.e(Constant.TAG, "findICCard:" + atr);
        }

        @Override
        public void findRFCard(String uuid) throws RemoteException {

        }

        @Override
        public void onError(int code, String message) throws RemoteException {
            String error = "onError:" + message + " -- " + code;
            LogUtil.e(Constant.TAG, error);
        }

    };


}
